package com.dtda.edu.miaosha.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import com.dtda.edu.miaosha.bo.UserInfoBo;
import com.dtda.edu.miaosha.common.exception.BaseExcpController;
import com.dtda.edu.miaosha.service.UserService;

/**
 * @author 袁强
 * @version 2019年1月29日 上午11:21:52
 * 类说明  
 * @param <V>
 */
//@Controller
@RestController
@RequestMapping("/")
public class RegisterController<V> extends BaseExcpController{

	@Autowired
	private UserService userService;
	
	@RequestMapping("/goRegister")
	public ModelAndView goRegister(){
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("/user/register");
		return modelAndView;
	}
	
	
	@RequestMapping("/doRegister")
	@ResponseBody
	public Map<String, String> doRegister(HttpServletRequest request,@RequestParam String name,
			                              @RequestParam String age,
			                              @RequestParam String gender,
			                              @RequestParam String telphone,
			                              @RequestParam String code,   //手机验证码
								    //注册密码
			                              @RequestParam String encrptPassword){
		
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("code", "fail");  //默认返回失败
		map.put("message", "注册失败,请重新注册...");
		
		//后台校验传入的参数
		boolean nameIsNull = StringUtils.isEmpty(name);
		boolean ageIsNull = StringUtils.isEmpty(age);
		boolean genderIsNull = StringUtils.isEmpty(gender);
		boolean telphoneIsNull = StringUtils.isEmpty(telphone);
		boolean encrptPasswordIsNull = StringUtils.isEmpty(encrptPassword);
		
		if(nameIsNull || ageIsNull || genderIsNull || telphoneIsNull || encrptPasswordIsNull) {
			return map;
		}
		
		//校验验证码,
		//由于验证码接口条数太少,所以测试时先将该功能进行屏蔽
		String sessionCode = (String) request.getSession().getAttribute(telphone);
		Boolean codeEquals = StringUtils.equals(code, sessionCode);
		request.getSession().removeAttribute(telphone);
		if(! codeEquals) {
			map.put("message", "手机验证码错误,请重新输入!");
			return map;
		}
		
		UserInfoBo userInfoBo = new UserInfoBo();
		userInfoBo.setName(name);
		userInfoBo.setAge(Integer.valueOf(age));
		userInfoBo.setGender(Byte.valueOf(gender));
		userInfoBo.setTelphone(telphone);
		userInfoBo.setEncrptPassword(encrptPassword);
	    int row=userService.insertUserInfo(userInfoBo);
		if(row <= 0) {
			//request.getSession().setAttribute("telphone", "codeError");
			return map;
		}
		map.put("code", "sucess");
		map.put("message", "注册成功!");
		return map;
	}
}
